package com.worldwizards.smut.serialization;

import java.io.IOException;

public class FieldDesc {
	enum FIELDTYPE {PRIMATIVE,OBJECT,ARRAY}
	
	SerializedClassRecord _class;
	FIELDTYPE _fieldType;
	byte _typeCode;
	String _fieldName;
	SerializedStringRecord _className;
	public FieldDesc(SerializedObjectRoot root, SerializedClassRecord serializedClassRecord, BinaryParser parser) throws IOException, SerializationParsingException {
		_class = serializedClassRecord;
		_typeCode = parser.readByte();
		_fieldName = parser.readUTF();
		switch (_typeCode){
			case 'B':
			case 'C':
			case 'D':
			case 'F':
			case 'I':
			case 'J':
			case 'S':
			case 'Z':
				_fieldType = FIELDTYPE.PRIMATIVE;
				return;
			case '{':
				_fieldType = FIELDTYPE.ARRAY;
				_className = (SerializedStringRecord) root.parseContent(parser);
				return;
			case 'L':
				_fieldType = FIELDTYPE.OBJECT;
				_className = (SerializedStringRecord) root.parseContent(parser);
				return;
			default:
				throw new SerializationParsingException("Unexpected field type found: "+ 
						String.valueOf((char)_typeCode));
		}
	}
	public ValueRecord parse(SerializedObjectRoot root, BinaryParser parser) throws IOException, SerializationParsingException {
		switch (_fieldType){
			case PRIMATIVE:
				switch (_typeCode){
					case 'B':
						return new ValueRecord(this, new Byte(parser.readByte()));
					case 'C':
						return new ValueRecord(this, new Character(parser.readChar()));
					case 'D':
						return new ValueRecord(this,new Double(parser.readDouble()));
					case 'F':
						return new ValueRecord(this,new Float(parser.readFloat()));
					case 'I':
						return new ValueRecord(this,new Integer(parser.readInt()));
					case 'J':
						return new ValueRecord(this,new Long(parser.readLong()));
					case 'S':
						return new ValueRecord(this,new Short(parser.readShort()));
					case 'Z':
						return new ValueRecord(this, new Boolean(parser.readBoolean()));
				}
			case OBJECT:
				ParseObject po = root.parseContent(parser);
				return new ValueRecord(this,po);
			case ARRAY:
				return new ValueRecord(this,new Integer(parser.readInt())); // a guess that it contains a handle
		}
		return null;
	}
	public void dump(String prefix) {
		switch (_fieldType){
			case PRIMATIVE:
				System.out.println(prefix+"Primative Field: "+_fieldName+"  Type:  "+(char)_typeCode);
				break;
			case OBJECT:
				System.out.println(prefix+"Object Reference("+_fieldName+"): "+_className.getValue());
				break;
			case ARRAY:
				System.out.println(prefix+"Array Reference("+_fieldName+"): "+_className.getValue());
				break;
		}
		
		
	}
	public String getFieldName() {
		return _fieldName;
	}
	public SerializedClassRecord getDefiningClass() {
		return _class;
	}
	

}
